import { isBoolean } from 'lodash'
import Vue from 'vue'
import messageCmp from './index.vue'

const messageConstructor = Vue.extend(messageCmp)
let instances = []
let seed = 1
let zIndex = 2001
let messageIndex = 0
let message = (props) => {
    if (typeof props == 'string') {
        props = {
            message: props,
            type: 'info'
        }
    }
    let { message, type, duration, dangerouslyUseHTMLString, center, once, customColor } = props
    if (once && isBoolean(once) && instances.length == 1){
        return false
    }
    dangerouslyUseHTMLString = dangerouslyUseHTMLString && Boolean(dangerouslyUseHTMLString) || false
    center = center && Boolean(center) || false
    const messageInstances = new messageConstructor({
        el: document.createElement('div'),
        data() {
            return {
                message: message || type || 'info',
                dangerouslyUseHTMLString,
                center,
                customColor,
                type: type || 'info',
            }
        },
    })
    let top = 20
    let id = `message_${seed}`
    seed++
    document.body.appendChild(messageInstances.$el)
    messageInstances.id = id
    instances.forEach(item => {
        top += item.$el.offsetHeight + 16
    })
    messageInstances.styleTop = top
    instances.push(messageInstances)
    messageInstances.messageStatus(true, zIndex, messageIndex)
    messageIndex++
    zIndex++
    // 过了 duration 时间后隐藏
    duration = duration ? duration : 3000
    setTimeout(() => {
        let length = instances.length
        messageInstances.messageStatus(false, zIndex, messageIndex)
        messageIndex--
        let offsetHeight = messageInstances.$el.offsetHeight
        let index = instances.findIndex(e => e.id === messageInstances.id)
        if (length > 1) {
            for (let i = index; i < length; i++) {
                let el = instances[i].$el
                el.style.top =
                    parseInt(el.style['top'], 10) - offsetHeight - 16 + 'px'
            }
        }
        instances.splice(index, 1)
        if (instances.length >= 9999) {
            zIndex = 2001
        }
    }, duration)
}

message.error  = (props) => {
    if (typeof props == 'string') {
        props = {
            message: props,
            type: 'error'
        }
    }
    message(props)
}
message.warning  = (props) => {
    if (typeof props == 'string') {
        props = {
            message: props,
            type: 'warning'
        }
    }
    message(props)
}
message.success  = (props) => {
    if (typeof props == 'string') {
        props = {
            message: props,
            type: 'success'
        }
    }
    message(props)
}
Vue.prototype.$message = message
window.$message = message
export default message